local skynet = require "skynet"
local s = require "service"

s.resp.register = function(source, fd, msg, ...)
    local cmd = msg.cmd
    local username = msg.username
    local pwd = msg.password1
    local pwd2 = msg.password2

    -- 查找username是否使用了
    local bNotExist = skynet.call("mysql_node", "lua", "check_username", username)
    if bNotExist then
        -- TODO: 校验密码安全性
        if pwd == "" then
            skynet.send(source, "lua", "send_error_msg", fd, cmd, -1, "密码不能为空")
            return
        end

        if pwd ~= pwd2 then
            skynet.send(source, "lua", "send_error_msg", fd, cmd, -1, "两次密码不一致")
            return
        end

        local bSuccess, id = skynet.call("mysql_node", "lua", "register", username, pwd)
        if bSuccess then
            local retMsg = {}
            retMsg.cmd = cmd
            retMsg.username = username
            retMsg.id = id
            skynet.send(source, "lua", "send_by_fd", fd, retMsg, "login.RetRegister")
        else
            skynet.send(source, "lua", "send_error_msg", fd, cmd, -1, "注册失败")
        end

    else
        skynet.send(source, "lua", "send_error_msg", fd, cmd, -1, "用户名已存在")
    end
end

s.start(...)
